'use strict';

const { Controller } = require('egg');
const { Op } = require('sequelize');

class BaseController extends Controller {
  constructor(ctx, serviceName) {
    super(ctx);
    this.serviceName = serviceName;
  }

  async index() {
    const { ctx } = this;
    const { pageNo, pageSize, ...query } = ctx.query;
    const page = Number(pageNo) || 1;
    const size = Number(pageSize) || 10;
    let where = this.getListQuery({
      ...query,
      pageNo: undefined,
      pageSize: undefined
    });
    const list = await ctx.service[this.serviceName].getPage(where, page, size);
    ctx.success(list);
  }
  getListQuery(query) {
    const where = {};
    for (const queryKey in query) {
      if (query[queryKey]) {
        if (queryKey.includes('_id')) {
          where[queryKey] = query[queryKey];
        } else {
          where[queryKey] = {
            [Op.like]: `%${query[queryKey]}%`,
          }
        }
      }
    }
    return where;
  }

  async create() {
    const { ctx } = this;
    const data = ctx.request.body;
    await ctx.service[this.serviceName].create(data);
    ctx.success(data, 200);
  }

  async update() {
    const { ctx } = this;
    const id = ctx.params.id;
    const infos = ctx.request.body;
    if (!id) throw new Error('必须传递ID参数');
    if (Object.keys(infos).length === 0) throw new Error('请传递修改的内容');
    await ctx.service[this.serviceName].update(id, infos);
    ctx.success(id, 200);
  }

  async destroy() {
    const uid = Number(this.ctx.params.id);
    if (!uid) throw new Error('ID 有误');
    await this.ctx.service[this.serviceName].deleteById(uid);
    this.ctx.success(uid);
  }

  async show() {
    const { ctx } = this;
    const id = ctx.params.id;
    const result = await ctx.service[this.serviceName].findOne(id);
    ctx.success(result);
  }

  async allList() {
    const { ctx } = this;
    const where = this.getListQuery(ctx.query);
    const result = await ctx.service[this.serviceName].allList(where);
    ctx.success(result);
  }
}

module.exports = BaseController;
